package com.lw.leetcode.stack.a;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * stack
 * 1047. 删除字符串中的所有相邻重复项
 *
 * @author liw
 * @version 1.0
 * @date 2021/7/25 20:57
 */
public class RemoveDuplicates {

    public String removeDuplicates(String s) {
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            if (!stack.isEmpty() && stack.peek() == chars[i]) {
                stack.pop();
            } else {
                stack.add(chars[i]);
            }
        }
        int i = length;
        while (!stack.isEmpty()) {
            chars[--i] = stack.pop();
        }
        return String.valueOf(chars, i, length - i);
    }
}
